import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { RootState } from '@/store'
import {
  addHistory,
  clearHistory,
  clearSuggestion,
  getSuggestion,
} from '@/store/action/search'
import classnames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import DOMPurify from 'dompurify'
import { removeLocalHistories } from '@/utils/storage'
import history from '@/utils/history'

const highlight = (res: string, key: string) => {
  const reg = new RegExp(`(${key})`, 'gi')
  return res.replace(reg, `<span>$1</span>`)
}

export default function Search() {
  const dispatch = useDispatch()

  const { suggestion, histories } = useSelector(
    (state: RootState) => state.search
  )

  const [keyword, setKeyword] = useState('')

  const timerId = useRef(-1)

  const handleChange = (value: string) => {
    setKeyword(value)

    window.clearTimeout(timerId.current)
    timerId.current = window.setTimeout(() => {
      if (!value) return
      dispatch(getSuggestion(value))
    }, 500)
  }

  const handleClear = () => {
    dispatch(clearSuggestion())
    setKeyword('')
  }

  const handleSearch = () => {
    if (!keyword) return
    dispatch(addHistory(keyword))
    gotoSearchResultPage(keyword)
  }

  const handleClearHistory = () => {
    dispatch(clearHistory())
    removeLocalHistories()
  }

  const gotoSearchResultPage = (keyword: string) => {
    dispatch(addHistory(keyword))

    history.push('/search/result?q=' + keyword)
  }

  useEffect(() => {
    return () => {
      window.clearTimeout(timerId.current)
    }
  }, [])

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span onClick={handleSearch} className="search-text">
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyword}
              onChange={(e) => handleChange(e.target.value.trim())}
              onKeyUp={(e) => {
                if (e.key === 'Enter') handleSearch()
              }}
            />

            {/* 清空输入框按钮 */}
            <Icon
              hidden={!keyword}
              type="iconbtn_tag_close"
              className="icon-close"
              onClick={() => handleClear()}
            />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      <div className="history" hidden={!!keyword}>
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={handleClearHistory}>
            <Icon type="iconbtn_del" />
            清除全部
          </span>
        </div>

        <div className="history-list">
          {histories.map((item, index) => (
            <span
              onClick={() => gotoSearchResultPage(item)}
              key={index}
              className="history-item"
            >
              {item}
              <span className="divider"></span>
            </span>
          ))}
        </div>
      </div>

      {/* 搜素建议结果列表 */}
      <div hidden={!keyword} className={classnames('search-result', 'show')}>
        {suggestion.map((item, index) => (
          <div
            key={index}
            className="result-item"
            onClick={() => gotoSearchResultPage(item)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div
              className="result-value"
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(highlight(item, keyword)),
              }}
            ></div>
          </div>
        ))}
      </div>
    </div>
  )
}
